package com.tanguy.user.ui.me.activity.wallet

import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.View
import cn.sinata.xldutils_kotlin.activity.WebViewActivity
import cn.sinata.xldutils_kotlin.adapter.BaseRecyclerAdapter
import cn.sinata.xldutils_kotlin.utils.SpanBuilder
import com.jakewharton.rxbinding2.widget.RxTextView
import com.mdchuxing.user.custom.SpaceItemDecoration
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.bean.Price
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.ui.me.adapter.SelectPriceAdapter
import com.tanguy.user.utlis.extend.click
import com.tanguy.user.utlis.extend.loge
import com.tanguy.user.utlis.extend.requestSucceed
import com.tanguy.user.utlis.extend.visibility
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_wallet.*
import org.jetbrains.anko.backgroundDrawable
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import org.jetbrains.anko.toast
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * Created by dab on 2017/10/10 0010 10:04
 * 钱包页面
 */
class WalletActivity : ImmersionTitleActivity() {

    override fun setContentViewRes(): Int = R.layout.activity_wallet
    val prices = arrayListOf(Price(100), Price(200), Price(500), Price(1000), Price(2000), Price(5000))
    val adapter by lazy {
        SelectPriceAdapter(prices)
    }
    var selectPrice = 0.0
    var price = 0.0//支付金额
    override fun initView() {
        super.initView()
        title = "我的钱包"
        titleBar.addRightButton("充值记录", onClickListener = View.OnClickListener {
            startActivity<RechargeRecordActivity>()
        })

        rv_select_price.setHasFixedSize(true)
        rv_select_price.addItemDecoration(SpaceItemDecoration(20))
        rv_select_price.layoutManager = GridLayoutManager(this, 3).apply {
            orientation = GridLayoutManager.VERTICAL
            isSmoothScrollbarEnabled = true
        }
        rv_select_price.adapter = adapter
        //默认选择第一个
        selectPrice(0)
        adapter.setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
            override fun onItemClick(view: View?, position: Int) {
                selectPrice(position)
            }
        })
        val priceString = "点击我要去充值，即表示已经同意唐吉《充返活动协议》"
        tv_agreement.text = SpanBuilder(priceString).color(this@WalletActivity, priceString.length - 8, priceString.length , R.color.color_fb408e)
                .build()
        tv_agreement.onClick {
            startActivity<WebViewActivity>("url" to Const.AppText.RECHARGE_REWARD_RULES, "title" to "充返活动协议")
        }
    }

    override fun initEvent() {
        super.initEvent()
        click(tv_other) { setOtherMoney() }
        click(btn_submit) {
            if (price <= 0.0) {
                toast("请选择或输入金额")
                return@click
            }
            startActivity<PayActivity>("payMoney" to price)
        }
        RxTextView.textChanges(et_input)
                .debounce(1000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (!TextUtils.isEmpty(it)) {
                        imputed(it.toString().toDouble())
//                        getRules(-1, if (TextUtils.isEmpty(it)) 0 else it.toString().toInt())
                    } else {
                        if (et_input.visibility == View.VISIBLE) {
                            tv_available.text = "送0元，可得0元余额"
                            price = 0.0
                        }
                    }
                }
    }

    private fun selectPrice(position: Int) {
        selectPrice = prices[position].price.toDouble()
        adapter.selectPrice = position
        adapter.notifyDataSetChanged()
        visibility(et_input,false)
        visibility(image,true)
        tv_send.text = "充值0元"
        tv_available.text = "送0元，可得0元余额"
        tv_other.backgroundDrawable = resources.getDrawable(R.drawable.corner_price_normal)
        tv_other.textColor = resources.getColor(R.color.textColor)
//        getRules(position, selectPrice)
        imputed(selectPrice)
    }

    /**
     * 计算价格
     */
    private fun imputed(selectPrice: Double) {
        HttpManager.getMyMoney(selectPrice)
                .requestSucceed(this) {
                    loge(selectPrice.toString() + it.toString(), 2)
                    val rewards = it.get("rewards")?.asDouble
                    var rewardsMoney = 0.0
                    if (rewards != null) {
                        rewardsMoney = rewards * selectPrice / 100
                        if (rewards <= 0.0) {
                            val maxRewa = it.get("maxRewa")?.asDouble
                            if (maxRewa != null && maxRewa > 0.0) {
                                rewardsMoney = maxRewa * selectPrice / 100
                            }
                        }
                    }
                    val priceString = String.format(Locale.CHINA, "充值%.2f元", selectPrice)
                    tv_send.text = SpanBuilder(priceString).color(this@WalletActivity, 2, priceString.length - 1, R.color.color_fb408e)
                            .size(2, priceString.length - 1, 25).build()
                    tv_available.text = String.format(Locale.CHINA, "送%.2f元，可得%.2f元余额", rewardsMoney, rewardsMoney + selectPrice)
                    price = selectPrice
                }

    }

    private fun setOtherMoney() {
        adapter.selectPrice = -1
        selectPrice = 0.0
        adapter.notifyDataSetChanged()
        tv_other.backgroundDrawable = resources.getDrawable(R.drawable.corner_price_press)
        tv_other.textColor = resources.getColor(R.color.color_fb408e)
        visibility(image,false)
        visibility(et_input,true)
        et_input.setText("")
        tv_send.text = "其他金额"
        price = 0.0
        tv_available.text = "送0元，可得0元余额"
    }

}